package com.kfm.web;

import com.kfm.model.KfmUser;
import com.kfm.service.UerService;
import com.kfm.util.Constant;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/login.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理登录
        String captcha = req.getParameter("verCode");
        boolean ver = CaptchaUtil.ver(captcha, req);
        if (!ver) {
            System.out.println("登录失败");
            resp.sendRedirect("/");
            return;
        }
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        try {
            UerService uerService = new UerService();
            KfmUser login = uerService.login(username, password);
            if (login == null) {
                System.out.println("登录失败");
                resp.sendRedirect("/");
                return;
            }
            System.out.println("登录成功");
            req.getSession().setAttribute(Constant.LOGIN_USER_KEY, login);
            resp.sendRedirect("/welcome");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
